#pragma once
#include"Log.hpp"
#include"Connection.hpp"
#include"Common.hpp"
#include"InetAddr.hpp"

using namespace LogModule;
#define SIZE 1024

class Channel:public Connection
{
    public:
    Channel(int sockfd,const InetAddr& client_addr):_sockfd(sockfd),_client_addr(client_addr)
    {
        SetNonBlock(_sockfd);
    }
    void Recver()override
    {
        char buffer[1024];
        while(true)
        {
            buffer[0]=0;
            ssize_t n=recv(_sockfd,buffer,SIZE-1,0);
            if(n>0)
            {
                buffer[n]=0;
                _inbuffer+=buffer;
            }
            else if(n==0)
            {
                Excepter();
                return;
            }
            else
            {
                if(errno==EAGAIN||errno==EWOULDBLOCK)
                {
                    break;
                }
                else if (errno==EINTR)
                {
                    continue;
                }
                else
                {
                    Excepter();
                    return;
                }
                
            }
        }
        LOG(LogLevel::DEBUG)<<"CHANNEL:INBUFFER:\n"<<_inbuffer;
        if(!_inbuffer.empty())
        {
            _outbuffer+=_handler(_inbuffer);
        }
        if(!_outbuffer.empty())
        {
            Sender();
        }
    }
    void Sender()override
    {
        while(true)
        {
            ssize_t n=send(_sockfd,_outbuffer.c_str(),_outbuffer.size(),0);
            if(n>0)
            {
                _outbuffer.erase(0,n);
                if(_outbuffer.empty())
                {
                    break;
                }
            }
            else if(n==0)
            {
                break;
            }
            else
            {
                if(errno==EAGAIN||errno==EWOULDBLOCK)
                {
                    break;
                }
                else if (errno==EINTR)
                {
                    continue;
                }
                else
                {
                    Excepter();
                    return;
                }
            }
        }
        if(!_outbuffer.empty())
        {
            
        }
    }
    void Excepter()override
    {

    }
    int GetSockFd()override
    {

    }
    std::string& Inbuffer()
    {

    }
    void AppendOutBuffer(const std::string & out)
    {

    }
    ~Channel()
    {

    }
    private:
    int _sockfd;
    std::string _inbuffer;
    std::string _outbuffer;
    InetAddr _client_addr;
};

